package com.jarvis.du.baselibrary.cookie;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import okhttp3.Cookie;

/**
 * Author: dyj
 * Date: 2018/8/22 下午3:09
 * E-mail: duyangjun1991@163.com
 */

public class MemoryCookieStore implements JarvisCookieStore {

    private final ArrayList<Cookie> cookies = new ArrayList();
    private final Comparator<Cookie> cookieComparator = new CookieIdentityComparator();

    public MemoryCookieStore() {
    }


    public String toString() {
        return this.cookies.toString();
    }


    @Override
    public synchronized void addCookie(Cookie var1) {
        if (var1 != null) {
            Iterator it = this.cookies.iterator();

            while (it.hasNext()) {
                if (this.cookieComparator.compare(var1, (Cookie) it.next()) == 0) {
                    it.remove();
                    break;
                }
            }

            if (var1.expiresAt() > System.currentTimeMillis()) {
                this.cookies.add(var1);
            }
        }
    }

    @Override
    public void addCookies(List<Cookie> var1) {
        if (var1 != null) {
            Iterator var2 = var1.iterator();

            while (var2.hasNext()) {
                Cookie cooky = (Cookie) var2.next();
                this.addCookie(cooky);
            }
        }
    }

    @Override
    public List<Cookie> getCookies() {
        return Collections.unmodifiableList(this.cookies);
    }

    @Override
    public boolean clearExpired(long var1) {
        if (var1 <= 0L) {
            return false;
        } else {
            boolean removed = false;
            Iterator it = this.cookies.iterator();

            while (it.hasNext()) {
                if (((Cookie) it.next()).expiresAt() <= var1) {
                    it.remove();
                    removed = true;
                }
            }

            return removed;
        }
    }

    @Override
    public void clear() {
        this.cookies.clear();
    }
}
